#!/bin/bash
#
# Copyright (C) 2018 Western Digital Corporation or its affiliates.
#
# This file is released under the GPL.

scriptdir="$(cd "$(dirname "$0")" && pwd)"

zone_size=1
zone_capacity=1
if [[ ${1} == "-h" ]]; then
    echo "Usage: ${0} [OPTIONS]"
    echo "Options:"
    echo -e "\t-h Show this message."
    echo -e "\t-zone-cap Use null blk with zone capacity less than zone size."
    echo -e "\tany option supported by test-zbd-support script."
    exit 1
elif [[ ${1} == "-zone-cap" ]]; then
    zone_size=4
    zone_capacity=3
    shift
fi

for d in /sys/kernel/config/nullb/*; do [ -d "$d" ] && rmdir "$d"; done
modprobe -r null_blk
modprobe null_blk nr_devices=0 || exit $?
for d in /sys/kernel/config/nullb/*; do
    [ -d "$d" ] && rmdir "$d"
done
modprobe -r null_blk
[ -e /sys/module/null_blk ] && exit $?
modprobe null_blk nr_devices=0 &&
    cd /sys/kernel/config/nullb &&
    mkdir nullb0 &&
    cd nullb0 || exit $?

if ((zone_capacity < zone_size)); then
    if [[ ! -w zone_capacity ]]; then
        echo "null blk does not support zone capacity"
        exit 1
    fi
    echo "${zone_capacity}" > zone_capacity
fi

echo 1 > zoned &&
    echo "${zone_size}" > zone_size &&
    echo 0 > completion_nsec &&
    echo 4096 > blocksize &&
    echo 1024 > size &&
    echo 1 > memory_backed &&
    echo 1 > power || exit $?

"${scriptdir}"/test-zbd-support "$@" /dev/nullb0
